package mapper.datasource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class DataSourceContextHolder {

    private static Map<Object, Object> targetDataSourcesCache = new HashMap<>();

    // 默认数据源
    public static final String DEFAULT_DATASOURCE = "default";

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    // 设置数据源名
    public static void setCurrentDatasourceName(String dbType) {
        contextHolder.set(dbType);
    }

    // 获取数据源名
    public static String getCurrentDatasourceName() {
        return (contextHolder.get());
    }

    public static Map<Object, Object> getTargetDataSources() {
        return targetDataSourcesCache;
    }

    public static DataSource get(String key) {
        return (DataSource) targetDataSourcesCache.get(key);
    }

    public synchronized static void put(String name, DataSource dataSource) {
        targetDataSourcesCache.put(name, dataSource);
    }

    public static boolean containsKey(String key) {
        return targetDataSourcesCache.containsKey(key);
    }

    // 清除数据源名
    public static void clear() {
        contextHolder.remove();
        targetDataSourcesCache.clear();
    }
}

